package com.example.tobebigfe.jsbridge

import android.app.Activity
import android.webkit.WebView
import org.json.JSONObject
import android.content.Intent
import android.provider.MediaStore
import android.net.Uri


class JSBridgeImage(val activity: WebActivity, webView: WebView) : BridgeModuleBase(webView) {

    private val REQ_CODE = 200

    override fun callFunc(func: String, callbackId: String, arg: JSONObject) {
        when (func) {
            "pickPhotos" -> pickPhotos(callbackId, arg)
        }
    }

    private fun pickPhotos(callbackId: String, arg: JSONObject) {
        // 创建去系统选图片的意图
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        activity.startActivityForCallback(intent, REQ_CODE) { requestCode: Int, resultCode: Int, result: Intent? ->
            // 不是对应的requestCode
            if (REQ_CODE != requestCode) {
                return@startActivityForCallback false
            }

            val json = JSONObject()

            if (resultCode == Activity.RESULT_OK) {
                val selectedImage = result?.data as Uri
                val mimeType = activity.contentResolver.getType(selectedImage)
                val type = if (mimeType?.startsWith("video/") == true) "video" else "image"
                json.put("success", true)
                json.put("type", type)
                json.put("file", selectedImage.toString())
            } else {
                json.put("success", false)
                json.put("canceled", resultCode == Activity.RESULT_CANCELED)
                json.put("error", "Result code is $resultCode")
            }

            callback(callbackId, json)
            true
        }
    }

}